/*
 * @Author: 曹捷
 * @Date: 2019-08-20 09:45:47
 * @LastEditors: 曹捷
 * @LastEditTime: 2020-11-10 19:34:52
 * @Description: 当前是否有请求   用于骨架遮盖
 */

const request = {
    state: {
        // 是否展示loading的状态，超时才展示loading
        loading: false,
        // 请求的开始到结束状态
        requestd: false,
        // 请求超时展示loading默认时间 ms
        timeOut: 150,
        requestStatus: {}
    },
    mutations: {
        /**
         * 请求开始 在超过 规定的超时时间之后 展示loading 骨架
         */
        startRequest: (state, value) => {
            // console.log('startRequest', new Date().getTime())
            Object.keys(state.requestStatus).forEach(element => {
                let time = element.split('_')[1]
                if (new Date().getTime() - time > 15 * 1000) {
                    console.log('new Date().getTime() - time', new Date().getTime() - time)
                    delete state.requestStatus[element]
                }
            });
            state.requestStatus[value] = 1
            state.requestd = true
            // console.log('state.requestd', state.requestd)
            /**
             * 如果请求在 规定的超时时间 之内完成  不展示loading状态
             * 1、避免出现一闪一闪的情况
             * 2、避免IOS转场动画前一页出现loading 跳转页面也出现loading
             */
            setTimeout(() => {
                if (state.requestStatus[value] && state.requestStatus[value] < 0) {
                    delete state.requestStatus[value]
                } else {
                    state.loading = true
                }
                request.mutations.endLoad(state)
            }, state.timeOut);
            /**
             * 为了避免请求还没有返回就退出页面 导致无法触发请求结束 超时 自动结束
             */
            setTimeout(() => {
                delete state.requestStatus[value]
                request.mutations.endLoad(state)
            }, 1000 * 10);
        },
        /**
         * 请求结束
         * 判断是否是最后一个请求，关闭loading
         */
        endRequest: (state, value) => {
            // console.log('value: ', value);
            // let n = new Date().getTime()
            // let time = value.split('_')[1]
            // console.log('endRequest', value, n, n - time)
            if (state.requestStatus[value]) {
                delete state.requestStatus[value]
            } else {
                state.requestStatus[value] = -1
            }
            request.mutations.endLoad(state)
        },
        endLoad: (state) => {
            // console.log('state', Object.keys(state.requestStatus).length)
            if (Object.keys(state.requestStatus).length === 0) {
                setTimeout(() => {
                    // console.log('end')
                    state.loading = false
                    state.requestd = false
                }, 100);

            }
        }
    },
    actions: {
    },
    getters: {
        loading: state => state.loading,
        requestd: state => state.requestd,
    }
}

export default request


